package org.projectwithoutname.handler;
import model.Workspace;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.ui.IPerspectiveDescriptor;
import org.eclipse.ui.IPerspectiveRegistry;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.internal.WorkbenchPlugin;
import org.projectwithoutname.commons.Commons;
import org.projectwithoutname.ui.pages.MainPage;
import org.projectwithoutname.ui.util.Hide;
import org.projectwithoutname.ui.view.SuperView;


@SuppressWarnings("restriction")
public class BackActionHandler extends AbstractHandler implements IHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		
		IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
		IWorkbenchPage page = window.getActivePage();
		IPerspectiveRegistry perspectiveRegistry = WorkbenchPlugin.getDefault().getPerspectiveRegistry();
		SuperView superView = (SuperView) page.findView(page.getPerspective().getDescription());
		Hide manager = superView.getHide();
		Workspace workspace = superView.root;
		String toClosePerspectiveID = page.getPerspective().getId();
		String toOpenPerspectiveID = manager.getLastHide(Commons.LEFT);
		
		
		try {
//			closing perspective
			IPerspectiveDescriptor toClose = perspectiveRegistry.findPerspectiveWithId(toClosePerspectiveID);
			page.closePerspective(toClose, true, false);
			manager.forwardAct(toClosePerspectiveID);
			
//			opening perspective
			IPerspectiveDescriptor toOpen = perspectiveRegistry.findPerspectiveWithId(toOpenPerspectiveID);
			String toNotify = toOpen.getDescription();
			page.setPerspective(toOpen);
			SuperView view = (SuperView) page.findView(toNotify);
			view.notify(manager);
			view.notify(workspace);
			if (page.findView(toNotify) instanceof MainPage){
				((MainPage)page.findView(toNotify)).refresh();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
		}
		return null;
	}

}
